package br.ufpe.cin.camid.core.events;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.spi.TypeListener;

public class EventBusListener implements TypeListener{

	private EventBus eventBus;
	
	private Class<? extends Annotation> annotationDefinition;
	
	public EventBusListener(EventBus eventBus, Class<? extends Annotation> annotationDefinition)
	{
		this.eventBus = eventBus;
		this.annotationDefinition = annotationDefinition;
	}
	
	@Override
	public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) 
	{
		Class<?> definition = type.getRawType();
		Method[] methods = definition.getDeclaredMethods();
		for(Method method : methods)
		{
			if(method.isAnnotationPresent(Subscribe.class) && method.isAnnotationPresent(annotationDefinition))
			{
				encounter.register(new EventBusInjectionListener<I>(eventBus));
			}
		}
	}

}
